local magnetDX = 25
local magnetDY = 45
local magnetR = 0
local magnetRange = 150

local fX = 0
local fY = 0
local magnetActive

magnetX = 0
magnetY = 0

local hasBall = false

function initMagnet()
	magnetX = 0
	magnetY = 0
    magnet = love.graphics.newImage("Content/magnet.png")
end

function updateMagnet(dt)
        magnetX = playerX + magnetDX
        magnetY = playerY + magnetDY-50
        magnetR = math.atan2((love.mouse.getY() - magnetY),(cameraX + love.mouse.getX()- magnetX))
        --mouse stuff
	if love.mouse.isDown("r") then
           distance = math.sqrt((magnetX-balls[0]:getX())*(magnetX-balls[0]:getX())+(magnetY-balls[0]:getY())*(magnetY-balls[0]:getY()) )
           a = math.atan2((balls[0]:getY() - magnetY),(balls[0]:getX() - magnetX))
           fX = math.cos(a)*100
           fY = math.sin(a)*100
	   if hasBall then
		balls[0]:applyImpulse(fX,fY)
		hasBall = false
	   end
        elseif love.mouse.isDown("l") then
           distance = math.sqrt((magnetX-balls[0]:getX())*(magnetX-balls[0]:getX())+(magnetY-balls[0]:getY())*(magnetY-balls[0]:getY()) )
	   tipX = math.cos(magnetR)*30+magnetX
	   tipY = math.sin(magnetR)*30+magnetY
           a = math.atan2((tipY - balls[0]:getY()),(tipX - balls[0]:getX()))
	   if distance > 30 and distance < 800 then
		fX = math.cos(a)*500
        	fY = math.sin(a)*500
	        balls[0]:applyForce(fX,fY)
		hasBall = false
           elseif distance <= 30 then
		hasBall = true
		balls[0]:setLinearVelocity( 0, 0 )
		balls[0]:setX(tipX)
		balls[0]:setY(tipY)
	   end
        end
end


function drawMagnet()
        love.graphics.draw( magnet, magnetX, magnetY, magnetR, 1, 1, 0, 20 )
        love.graphics.line(math.cos(magnetR)*30+magnetX,math.sin(magnetR)*30+magnetY,magnetX,magnetY);
        love.graphics.circle("fill", fX, fY, 5, 20)
end
